#!/usr/local/bin/perl

# This script is part of the HTC scalability test and works by installing
# an "at" job to run a command at a specific time. Another script, the
# distributor, calls this to install the at job on many machines so that
# all the machines will run the command at a given time in an effort to
# trigger simultaneous demand on the HTC server from multiple machines. To
# simulate even greater demand, the job can fork several copies of itself,
# or children, (see the # --children flag) to place even greater demands on
# the server.

use strict;
use Getopt::Long;
use File::Temp qw/tempfile/;
use FindBin qw($Bin);

my %options;
GetOptions ( \%options, "help", "command=s", "time=s",
                        "children=i", "debug", "version" );

my $time = $options{"time"};
my $children = $options{"children"} || 10;
my $command = $options{"command"};
my $version = $options{"version"};

# The directory where the temporary file containing the command
# should be written.
my $dir = "/usr/local/scratch/";

version() if $options{"version"};
usage() if $options{"help"};

# Temp file will remain because we're requesting the filename.
# See tehe File::Temp documentation...
my ($fh, $filename) = tempfile( DIR => $dir );
print $fh $command;
close $fh;

my $invoker = "$Bin/invoker.pl";
unless (-e $invoker && -x $invoker) {
    die "Cannot find invoker.pl. It should be in the same directory " .
        "as this script.";
}

`echo "$invoker --children $children --filename $filename" | at $time 2>/dev/null`;

sub usage {
    my $usage = <<"    _USAGE";
    --command    The command to be invoked.

    --help       Display this help screen.

    --time       The time to invoke the command (eg. 2:33pm)

    --children   How many processes to fork to execute the command

    --debug      Display additional debugging information

    _USAGE

    print $usage;
    exit;
}

sub version {
    print "Version $version\n\n";
    exit;
}
